/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.util;

import com.googlecode.bambole.controller.util.ConfigurationUtil;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
public class SendEmailMessageUtil {

    public static boolean sendEmailMessage(String recipient, String subject, String messageBody) {

        final String smtpSettings[] = ConfigurationUtil.getSmtpSettings();

        if (smtpSettings == null) {
            return false;
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpSettings[1]);
        props.put("mail.smtp.socketFactory.port", smtpSettings[2]);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", smtpSettings[2]);

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpSettings[3], smtpSettings[4]);
            }
        });

        try {

            Message emailMessage = new MimeMessage(session);
            emailMessage.setFrom(new InternetAddress(smtpSettings[0]));
            emailMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
            emailMessage.setSubject(subject);
            emailMessage.setText(messageBody);

            Transport.send(emailMessage);

            return true;

        } catch (MessagingException e) {

            Logger.getAnonymousLogger().log(Level.SEVERE, "Messaging exception: {0}", e.getMessage());

            return false;
        }
    }
}
